package com.mpp.admin.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author mapp
 * @des 相册
 * @date 2019/2/15
 */
@Controller
@RequestMapping("/photo")
public class PhotoController {

    @Value("${photo.localtion-path}")
    private String phtotLocationPath;
    @Value("${photo.suffix}")
    private List<String> photoSuffix;

    @RequestMapping("/index")
    public String index(ModelMap modelMap) {
        // 读取目录下的图片名称
        File file = new File(phtotLocationPath);
        List<String> filePaths = new ArrayList<>();
        if (file.isDirectory()) {
            String[] files = file.list();
            if (files != null) {
                for (String fileName : files) {
                    if (photoSuffix.contains(StringUtils.substringAfterLast(fileName, "."))) {
                        filePaths.add(fileName);
                    }
                }
            }
        }
        modelMap.put("pathList", filePaths);
        return "photo";
    }

    @RequestMapping("/viewPhoto")
    public void viewPhoto(String path, HttpServletResponse response) {
        try(InputStream in = new FileInputStream(phtotLocationPath + File.separatorChar + path);
            ServletOutputStream out = response.getOutputStream()) {
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes);
            }
            out.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
